package lolnotepad;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author havlicekdom@gmail.com
 */
public class Reader implements ActionListener {

    final private static JPanel panel = new JPanel();
    final private static JPanel panel2 = new JPanel();
    final private static JPanel panel3 = new JPanel();
    final private JPanel searchPanel = new JPanel();
    final private JPanel mPanel = new JPanel();
    final ArrayList<String> champions;
    final ArrayList<String> roles;
    final ArrayList<String> leagues;
    static private String[] columnNames = {"Played as", "Role", "Lane opponent", "Dificulty", "Result", "Score", "Game type", "Current LP", "Current league"};

    public void create(Game[] g, final JFrame frame, final JButton bButton) {
        File inputFile = new File("./src/data.src");
        File tempFile = new File("./src/TempDataFile.src");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
            for (int i = 0; i < g.length; i++) {
                if (!(g[i].getChampion()).equals("")) {
                    writer.write(g[i].getChampion() + "#" + g[i].getRole() + "#" + g[i].getEnemy() + "#" + g[i].getDifficulty() + "#" + g[i].getResult() + "#" + g[i].getScore() + "#" + g[i].getGameType() + "#" + g[i].getPoints() + "#" + g[i].getLeague() + "#" + g[i].getNotes() + "#");
                    writer.newLine();
                }
            }
            writer.close();
            if (!inputFile.delete()) {
                JOptionPane.showMessageDialog(null, "Couldn't create new data file");
            }
            if (!tempFile.renameTo(inputFile)) {
                JOptionPane.showMessageDialog(null, "Couldn't create new data file");
            }
            frame.remove(mPanel);
            frame.revalidate();
            frame.repaint();
            Reader reader = new Reader(frame, champions, roles, leagues);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Couldn't open data file");
            System.exit(1);
        }
    }

    public void search(Game[] g, String searchingFor, JFrame frame, JButton bButton) throws IOException {
        int length = 0;
        for (int i = 0; i < g.length; i++) {
            if (g[i].getChampion().toLowerCase().matches(searchingFor.toLowerCase() + "(.*)")) {
                length++;
            }
        }
        String[][] tableData = new String[length][9];
        int counter = 0;
        for (int i = 0; i < g.length; i++) {
            if (g[i].getChampion().toLowerCase().matches(searchingFor.toLowerCase() + "(.*)")) {
                tableData[counter][0] = g[i].getChampion();
                tableData[counter][1] = g[i].getRole();
                tableData[counter][2] = g[i].getEnemy();
                tableData[counter][3] = g[i].getDifficulty();
                tableData[counter][4] = g[i].getResult();
                tableData[counter][5] = g[i].getScore();
                tableData[counter][6] = g[i].getGameType();
                tableData[counter][7] = g[i].getPoints();
                tableData[counter][8] = g[i].getLeague();
                counter++;
            }
        }
        panel.removeAll();
        panel.revalidate();
        panel.repaint();
        searchPanel.removeAll();
        searchPanel.revalidate();
        searchPanel.repaint();
        mPanel.removeAll();
        mPanel.revalidate();
        mPanel.repaint();
        buildSearched(tableData, g, frame, bButton);
    }

    /**
     *
     * @param row = pointer at the certain table row that is supposed to be
     * shown
     * @param g = data from where we take the shown row
     */
    public void specific(final int row, final Game[] g, final JFrame frame, final JButton bButton) {       //function for showing specific row from data
        final JButton button = new JButton("Back");
        final JButton editButton = new JButton("Edit note");
        final JButton saveButton = new JButton("Save");
        final JButton deleteButton = new JButton("Delete note");
        final JLabel label1 = new JLabel("Champion: ");
        final JLabel label2 = new JLabel("Role: ");
        final JLabel label3 = new JLabel("Opponent: ");
        final JLabel label4 = new JLabel("Dificulty: ");
        final JLabel label5 = new JLabel("Result: ");
        final JLabel label6 = new JLabel("Score: ");
        final JLabel label7 = new JLabel("Game Type: ");
        final JLabel label8 = new JLabel("Current LP: ");
        final JLabel label9 = new JLabel("Current league: ");
        final JLabel label0 = new JLabel("Notes: ");
        final JComboBox cB1 = new JComboBox();
        final JComboBox cB2 = new JComboBox();
        final JComboBox cB3 = new JComboBox();
        final JComboBox cB4 = new JComboBox();
        final JTextField text4 = new JTextField(9);
        final JTextField text5 = new JTextField(9);
        final JTextField text6 = new JTextField(9);
        final JTextField text7 = new JTextField(9);
        final JTextField text8 = new JTextField(9);
        final JTextArea textArea = new JTextArea(5, 30);
        Font font = new Font("Verdana", Font.PLAIN, 11);
        textArea.setFont(font);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        final JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setBounds(10, 60, 780, 500);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setPreferredSize(new Dimension(700, 150));
        cB1.setEnabled(false);
        cB2.setEnabled(false);
        for (int i = 0; i < champions.size(); i++) {
            cB1.addItem(champions.get(i));
            cB3.addItem(champions.get(i));
        }
        cB3.setEnabled(false);
        for (int i = 0; i < roles.size(); i++) {
            cB2.addItem(roles.get(i));
        }
        cB4.setEnabled(false);
        for (int i = 0; i < leagues.size(); i++) {
            cB4.addItem(leagues.get(i));
        }
        text4.setEditable(false);
        text5.setEditable(false);
        text6.setEditable(false);
        text7.setEditable(false);
        text8.setEditable(false);
        textArea.setEditable(false);
        cB1.setSelectedItem(g[row].getChampion());
        cB2.setSelectedItem(g[row].getRole());
        cB3.setSelectedItem(g[row].getEnemy());
        cB4.setSelectedItem(g[row].getLeague());
        text4.setText(g[row].getDifficulty());
        text5.setText(g[row].getResult());
        text6.setText(g[row].getScore());
        text7.setText(g[row].getGameType());
        text8.setText(g[row].getPoints());
        textArea.setText(g[row].getNotes());
        if ((text7.getText()).equals("normal")) {
            text8.setVisible(false);
            label8.setVisible(false);
            cB4.setVisible(false);
            label9.setVisible(false);
        }
        panel2.add(label1);
        panel2.add(cB1);
        panel2.add(label2);
        panel2.add(cB2);
        panel2.add(label3);
        panel2.add(cB3);
        panel2.add(label4);
        panel2.add(text4);
        panel2.add(label5);
        panel2.add(text5);
        panel2.add(label6);
        panel2.add(text6);
        panel2.add(label7);
        panel2.add(text7);
        panel2.add(label8);
        panel2.add(text8);
        panel2.add(label9);
        panel2.add(cB4);
        panel3.add(label0);
        panel3.add(scrollPane);
        panel3.setBorder(new EmptyBorder(10, 250, 10, 300));
        panel2.add(panel3);
        panel2.add(saveButton);
        panel2.add(editButton);
        panel2.add(deleteButton);
        panel2.add(button);
        panel2.setVisible(true);
        panel3.setVisible(true);
        saveButton.setVisible(false);
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteButton.setVisible(false);
                button.setVisible(false);
                cB1.setEnabled(true);
                cB2.setEnabled(true);
                cB3.setEnabled(true);
                cB4.setEnabled(true);
                text4.setEditable(true);
                text5.setEditable(true);
                text6.setEditable(true);
                text7.setEditable(true);
                text8.setEditable(true);
                textArea.setEditable(true);
                editButton.setVisible(false);
                saveButton.setVisible(true);
            }
        });
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                g[row].setChampion(cB1.getSelectedItem().toString());
                g[row].setRole(cB2.getSelectedItem().toString());
                g[row].setEnemy(cB3.getSelectedItem().toString());
                g[row].setDifficulty(text4.getText());
                g[row].setResult(text5.getText());
                g[row].setScore(text6.getText());
                g[row].setGameType(text7.getText());
                g[row].setPoints(text8.getText());
                g[row].setLeague(cB4.getSelectedItem().toString());
                g[row].setNotes(textArea.getText());
                panel3.removeAll();
                panel3.repaint();
                panel3.revalidate();
                panel2.removeAll();
                panel2.repaint();
                panel2.revalidate();
                create(g, frame, bButton);
                JOptionPane.showMessageDialog(null, "Save succesful!");
            }
        });
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                g[row].unset();
                panel3.removeAll();
                panel3.repaint();
                panel3.revalidate();
                panel2.removeAll();
                panel2.repaint();
                panel2.revalidate();
                create(g, frame, bButton);
            }
        });
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel2.setVisible(false);
                panel3.setVisible(false);
                panel.setVisible(true);
                searchPanel.setVisible(true);
                bButton.setVisible(true);
                panel3.removeAll();
                panel3.repaint();
                panel3.revalidate();
                panel2.removeAll();
                panel2.repaint();
                panel2.revalidate();
            }
        });
    }

    public final void build(final Game[] g, final JFrame frame, final JButton bButton) throws IOException {
        String[][] tableData = new String[g.length][9];
        for (int i = 0; i < tableData.length; i++) {
            tableData[i][0] = g[i].getChampion();
            tableData[i][1] = g[i].getRole();
            tableData[i][2] = g[i].getEnemy();
            tableData[i][3] = g[i].getDifficulty();
            tableData[i][4] = g[i].getResult();
            tableData[i][5] = g[i].getScore();
            tableData[i][6] = g[i].getGameType();
            tableData[i][7] = g[i].getPoints();
            tableData[i][8] = g[i].getLeague();
        }
        final JLabel searchLabel = new JLabel("Search for champion played.");
        final JButton searchButton = new JButton("Search");
        final JTextField searchText = new JTextField(20);
        frame.setTitle("LoL Notepad - reading your notes");
        JTable table = new JTable(tableData, columnNames);
        final JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(980, 500));
        panel2.setPreferredSize(new Dimension(1000, 550));
        panel2.setVisible(false);
        panel2.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel3.setVisible(false);
        panel.setLayout(new FlowLayout());
        panel.removeAll();
        panel.add(scrollPane);
        panel.setVisible(true);
        searchPanel.add(searchLabel);
        searchPanel.add(searchText);
        searchPanel.add(searchButton);
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    search(g, searchText.getText(), frame, bButton);
                    frame.setCursor(Cursor.getDefaultCursor());
                } catch (IOException ex) {
                    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    JTable target = (JTable) e.getSource();
                    panel.setVisible(false);
                    searchPanel.setVisible(false);
                    bButton.setVisible(false);
                    int row = target.getSelectedRow();
                    specific(row, g, frame, bButton);
                }
            }
        });
    }

    /**
     *
     * @param data = data to print into table
     * @param g = array of Game objects
     * @param frame = main frame
     * @param bButton = button for closing currently running class
     */
    public void buildSearched(final String[][] data, final Game[] g, final JFrame frame, final JButton bButton) {
        if (data.length == 0) {
            JOptionPane.showMessageDialog(null, "No game found!");
            frame.remove(mPanel);
            frame.revalidate();
            frame.repaint();
            Reader reader = new Reader(frame, champions, roles, leagues);
        } else {
            final JButton button = new JButton("Back");
            JTable table = new JTable(data, columnNames);
            final JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(980, 500));
            mPanel.add(scrollPane);
            mPanel.add(button);
            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    if (e.getClickCount() == 1) {
                        JTable target = (JTable) e.getSource();
                        mPanel.remove(scrollPane);
                        mPanel.remove(button);
                        mPanel.revalidate();
                        mPanel.repaint();
                        mPanel.add(panel2);
                        int row = target.getSelectedRow();
                        specific(row, g, frame, bButton);
                    }
                }
            });
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    frame.remove(mPanel);
                    frame.revalidate();
                    frame.repaint();
                    Reader reader = new Reader(frame, champions, roles, leagues);
                }
            });
        }
    }

    /**
     *
     * @param frame = frame for whole app
     */
    public Reader(final JFrame frame, ArrayList<String> championsP, ArrayList<String> rolesP, ArrayList<String> leaguesP) {       //function for loading data into table
        champions = new ArrayList(championsP);
        roles = new ArrayList(rolesP);
        leagues = new ArrayList(leaguesP);
        try (BufferedReader input1 = new BufferedReader(new FileReader("./src/data.src"))) {
            int lines = 0;
            while (input1.read() != -1) {
                if (!(input1.readLine()).equals("")) {
                    lines++;
                }
            }
            input1.close();
            if (lines == 0) {
                JOptionPane.showMessageDialog(null, "No data to load, create a note first!");
                Writer writer = new Writer(frame, champions, roles, leagues);
            } else {
                try (BufferedReader input = new BufferedReader(new FileReader("./src/data.src"))) {
                    Game[] g = new Game[lines];
                    String currentLine;
                    String[] help;
                    int counter = 0;
                    while (lines > 0) {
                        currentLine = input.readLine();
                        help = currentLine.split("#");
                        g[counter] = new Game(help);
                        counter++;
                        lines--;
                    }
                    input.close();
                    final JButton bButton = new backButton().create(frame, mPanel);

                    build(g, frame, bButton);
                    mPanel.add(panel);
                    mPanel.add(panel2);
                    mPanel.add(searchPanel);
                    mPanel.add(bButton);
                    bButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                            panel.removeAll();
                            frame.setCursor(Cursor.getDefaultCursor());
                        }
                    });
                    mPanel.setPreferredSize(new Dimension(1000, 750));
                    panel.setBorder(new EmptyBorder(10, 10, 10, 10));
                    frame.setLayout(new FlowLayout());
                    frame.add(mPanel);
                    frame.pack();
                    JMenuBar menuBar = new Menu(frame, mPanel, champions, roles, leagues);
                    frame.setJMenuBar(menuBar);
                    frame.setVisible(true);
                    Rectangle rec = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
                    int width = (int) rec.getWidth();
                    int height = (int) rec.getHeight();
                    frame.setBounds(1, 3, width, height);
                    frame.addComponentListener(new ComponentAdapter() {
                        @Override
                        public void componentMoved(ComponentEvent e) {
                            frame.setLocation(1, 3);
                        }
                    });

                } catch (IOException ioe) {
                    System.exit(1);
                }
            }
        } catch (IOException ioe) {
            System.exit(1);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
